import { useState, useEffect } from 'react';
import { 
  Card, Table, Button, Modal, Form, Input, Select, 
  Tag, Space, message, Popconfirm 
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { todoAPI } from '../services/api';
import { Todo } from '../types';

const { Option } = Select;

const TodoList = () => {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingTodo, setEditingTodo] = useState<Todo | null>(null);
  const [form] = Form.useForm();

  // 获取待办事项列表
  const fetchTodos = async () => {
    try {
      const response = await todoAPI.getList();
      setTodos(response.data);
    } catch (error) {
      message.error('获取待办事项失败');
    }
  };

  useEffect(() => {
    fetchTodos();
  }, []);

  // 处理模态框确认
  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingTodo) {
        await todoAPI.update(editingTodo.id, values);
        message.success('更新成功');
      } else {
        await todoAPI.create(values);
        message.success('创建成功');
      }
      setIsModalVisible(false);
      form.resetFields();
      setEditingTodo(null);
      fetchTodos();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await todoAPI.delete(id);
      message.success('删除成功');
      fetchTodos();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 处理编辑
  const handleEdit = (record: Todo) => {
    setEditingTodo(record);
    form.setFieldsValue({
      title: record.title,
      content: record.content,
      category: record.category,
      tags: record.tags,
      status: record.status,
    });
    setIsModalVisible(true);
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: any) => (
        <Tag color={category.color || 'blue'}>{category.name}</Tag>
      ),
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      render: (tags: any[]) => (
        <>
          {tags.map(tag => (
            <Tag color={tag.color || 'green'} key={tag.id}>
              {tag.name}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'completed',
      key: 'completed',
      render: (completed: boolean) => (
        <Tag color={completed ? 'success' : 'warning'}>
          {completed ? '已完成' : '未完成'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Todo) => (
        <Space>
          <Button 
            type="text" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          />
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="待办事项"
      extra={
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={() => {
            setEditingTodo(null);
            form.resetFields();
            setIsModalVisible(true);
          }}
        >
          新建待办
        </Button>
      }
    >
      <Table 
        columns={columns} 
        dataSource={todos}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={editingTodo ? '编辑待办' : '新建待办'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
          setEditingTodo(null);
        }}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select>
              <Option value="工作">工作</Option>
              <Option value="学习">学习</Option>
              <Option value="生活">生活</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="tags"
            label="标签"
          >
            <Select mode="tags" placeholder="请输入标签">
              <Option value="重要">重要</Option>
              <Option value="紧急">紧急</Option>
              <Option value="日常">日常</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value={0}>未完成</Option>
              <Option value={1}>已完成</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default TodoList; 